/**
 * @create 2022-05-02
 * @desc 给 console 插入当前所在[行，列]信息
 */

const {getBaseData} = require('../utils/index')

const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const types = require('@babel/types');

const {sourceCode, outputFn} = getBaseData();

const ast = parser.parse(sourceCode, {
    sourceType: 'unambiguous',
    plugins: ['jsx']
});

// 通过 astexplorer 确定需要判断的节点(console)，然后修改参数
traverse(ast, {
    CallExpression(path) {
        const {node} = path;
        if (types.isMemberExpression(node.callee) &&
        node.callee.object.name === 'console' &&
        ['log', 'error', 'warn', 'info'].includes(node.callee.property.name)) {
            const {line, column} = node.callee.loc.start;
            node.arguments.unshift(types.stringLiteral(`[info]: line: ${line}, column: ${column} \n: `))
        }
    }
});

const { code, map } = generate(ast);
outputFn(code)